//
//  SYApiManager.swift
//  SheYangBigData
//
//  Created by 叁拾叁 on 2020/8/11.
//  Copyright © 2020 叁拾叁. All rights reserved.
//

import Foundation
import Moya
import HandyJSON
import RxSwift



let ApiManagerProvider = MoyaProvider<SYApiManager>(endpointClosure: endpointMapping, requestClosure: requestTimeoutClosure, plugins:[])

public func endpointMapping<Target: TargetType>(target: Target) -> Endpoint {
    print("\n************************************************** separate *********************************************\n\n请求链接：\(target.baseURL)\(target.path) \n方法：\(target.method.rawValue) \n请求头：\(target.headers ?? [:])\n参数：\(String(describing: target.task.self))")
    //在这里设置你的HTTP头部信息
    return MoyaProvider.defaultEndpointMapping(for: target).adding(newHTTPHeaderFields: target.headers ?? [:])
}

//设置请求超时时间
private let requestTimeoutClosure = { (endpoint: Endpoint, done: @escaping MoyaProvider<SYApiManager>.RequestResultClosure) in
    do {
        var request = try endpoint.urlRequest()
        request.timeoutInterval = 60
        done(.success(request))
    } catch {
        return
    }
}

enum SYApiManager {
    
    case login(dic: [String: String])
    case yunweiList(page: Int, size: Int)
    case shouye
    case xiangmuList(dic: [String: String], page: Int, size: Int)
    case xiangmuDetail(String: String)
    case shebeiList(dic:[String: String], page: Int, size: Int)
    case sheDetail(id: String)
    case editDeviceDetail(dic: [String:String])
    case editYJchuli(dic:[String: String])
    case yijianqidong(dic: [String: String])
    case portList
    case portYuanshishuju(dic: [String: String],page: Int ,size: Int)
    case deviceType(String: String)
    case duankouList(dic:[String: String], page: Int, size: Int)
    case kongzhiqiList(id:String)
    case kongzhishebei(id:String,value:String)
    case xinjian (dic:[String :String])
    case yijianfankui (dic:[String: String])
    case duankoukaiguan(dic:[String: String])
    case xiaoxiclass(number: String, page: Int, size: Int)
    case xiaoxilist
    case xiugaimima(dic:[String: String])
    case chuanganqidetail(parentDeviceId: String,childDeviceId: String)
    case ensoredit(dic: [String: String])
    case xieyiList(dic: [String: String], page: Int, size: Int)


}

extension SYApiManager: TargetType {
    
    var headers: [String : String]? {
        
        let token: String = UserDefaults.standard.value(forKey: "token") as? String ?? ""
        let jwt: String = UserDefaults.standard.value(forKey: "jwt") as? String ?? ""
        return ["token": token, "Authorization": token, "jwt": jwt]
    }
    
    var baseURL: URL {
        switch self {
        case .login:
            return URL(string: IP+VERSION)!
        default:
            return URL(string: IP+VERSION)!
        }
    }
    
    var path: String {
        switch self {
        case .login(_): return LOGIN
        case .yunweiList(let page, let size): return String(format: "%@/%ld/%ld", YUNWEI_LIST, page, size)
        case .xiangmuList(dic: _,let page, let size): return String(format: "%@/%ld/%ld", XIANGMU_FENYE, page, size)
        case .xieyiList(dic: _, let page, let size): return String(format: "%@/%ld/%ld", XIEYI_LIST, page, size)
            
        case .shouye: return SHOUYE
        case .xiangmuDetail(let id): return String(format: "%@/%@",XIANGMU_DETAIL,id)
        case .shebeiList(dic: _, page: let page, size: let size): return String(format: "%@/%ld/%ld", SHEBEI_LIST, page, size)
            
        case .sheDetail(let id):
            return String(format: "%@/%@",SHEBEI_DETAIL,id)
        case .editDeviceDetail:
            return EDIT_DEVICE
        case .editYJchuli:
            return YUJINgCHULI
        case .yijianqidong(dic: _):
            return SETENABLE_DEVICE
        case .portList:
            return PORT_LIST
        case .portYuanshishuju(dic: _, page: let page, size: let size):
            return String(format: "%@/%ld/%ld", YUANSHISHUJU, page, size)
        case .deviceType(let id): return String(format: "%@/%@", DEVICETYPE,id)
        case .duankouList(dic:_,page: let page, size: let size):return String(format: "%@/%ld/%ld", DUANKOU_LIST, page, size)
        case .kongzhiqiList(let id):
            return String(format: "%@/%@", KONGZHIQIL_LIST,id)

        case .kongzhishebei(let id, let value):return String(format: "%@/%@/%@", SHEBEIKONGZHI, id, value)
        case .xinjian(dic: _):return  XINJIANSHEBEI
            
        case .yijianfankui(dic: _):return YIJIANFANKUI
        case .duankoukaiguan(dic: _):return DUANKOUZHAUNGTAI
        case .xiaoxiclass(let number, let page, let size):return String(format: "%@/%@/%ld/%ld", XIAOXI_CLASS,  number,page,size)
        case .xiaoxilist:return XIAOXI_LIST
        case .xiugaimima(dic: _):return XIUGAIMIMA
        case .chuanganqidetail(let parentDeviceId, let childDeviceId): return String(format: "%@/%@/%@",CHUANGGANQIDETAIL,parentDeviceId,childDeviceId )
        case .ensoredit(dic: _): return ENSOREDIT

        }
    }
    
    var method: Moya.Method {
        switch self {
        case .login,.yunweiList, .xiangmuList, .xieyiList, .shebeiList, .editDeviceDetail,.editYJchuli, .yijianqidong, .portYuanshishuju,.duankouList,.kongzhiqiList,.kongzhishebei,.xinjian,.yijianfankui,.duankoukaiguan,.xiugaimima,.ensoredit:
            return .post
        default:
            return .get
        }
    }
    
    var task: Task {
        switch self {
        case .login(let dic):
            return .requestParameters(parameters: dic, encoding: JSONEncoding.default)
            
        case .yunweiList( _, _):
            return .requestParameters(parameters: [:], encoding: JSONEncoding.default)

        case .xiangmuList(let dic,_,_):
            
            return .requestParameters(parameters: dic, encoding: JSONEncoding.default)
        case .xieyiList(let dic, _,_):
            return .requestParameters(parameters: dic, encoding: JSONEncoding.default)

        case .shebeiList( let dic, _, _):
            
            return .requestParameters(parameters: dic, encoding: JSONEncoding.default)
            
        case .editDeviceDetail(let dic):
            return .requestParameters(parameters: dic, encoding: JSONEncoding.default)
        case .editYJchuli(let dic):
            return .requestParameters(parameters: dic, encoding: JSONEncoding.default)
            
        case .yijianqidong(let dic):
            return .requestParameters(parameters: dic, encoding: JSONEncoding.default)
        case .portYuanshishuju(let dic,_,_):
            return .requestParameters(parameters: dic, encoding: JSONEncoding.default)
        case.duankouList(let dic,_,_):
            return .requestParameters(parameters: dic, encoding: JSONEncoding.default)
        case.kongzhiqiList(_):
            return .requestParameters(parameters: [:], encoding: JSONEncoding.default)
//        case.xiaoxilist:
//            return .requestParameters(parameters: [:], encoding: JSONEncoding.default)
        case.kongzhishebei(_,_):
            return .requestParameters(parameters: [:], encoding: JSONEncoding.default)
        case.xinjian(let dic):
            return .requestParameters(parameters: dic, encoding: JSONEncoding.default)
        case.yijianfankui(let dic):
            return .requestParameters(parameters: dic, encoding: JSONEncoding.default)
        case.duankoukaiguan(let dic):
            return .requestParameters(parameters: dic, encoding: JSONEncoding.default)
//        case.xiaoxiclass(_, _, _):
//        return .requestParameters(parameters: [:], encoding: JSONEncoding.default)
        case.xiugaimima(let dic):
            return .requestParameters(parameters: dic, encoding: JSONEncoding.default)
        case.ensoredit(let dic):
            return .requestParameters(parameters: dic, encoding: JSONEncoding.default)

        default:
            return .requestPlain
        }
    }
    
    var validate: Bool {
        return false
    }
    var sampleData: Data {
        return "".data(using: String.Encoding.utf8)!
    }
    
    func getImagesData(imgs: [UIImage]) -> [MultipartFormData] {
        
        var formDataAry:[MultipartFormData] = [MultipartFormData]()
        for (index,image) in imgs.enumerated() {
            //图片转成Data
            let data:Data = image.jpegData(compressionQuality: 0.7)!
            //根据当前时间设置图片上传时候的名字
            let now = Date()
            var dateStr: String = now.sy_toString(format: "yyyy-MM-dd HH:mm:ss")
            //别忘记这里给名字加上图片的后缀哦
            dateStr = dateStr.appendingFormat("-%i.jpeg", index)
            // MARK: - 对应服务端，这里的name必须为 "file"，fileName和mineType必须有值，headers只需要token，不然都会报错，提示未上传文件
            let formData: MultipartFormData = MultipartFormData(provider: .data(data), name: "file", fileName: dateStr, mimeType: "image/jpeg")
            formDataAry.append(formData)
        }
        
        return formDataAry
    }
}



// MARK: 取消所有请求
func cancelAllRequest() {
    //    ApiManagerProvider.manager.session.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in
    //        dataTasks.forEach { $0.cancel() }
    //        uploadTasks.forEach { $0.cancel() }
    //        downloadTasks.forEach { $0.cancel() }
    //    }
    //
    //    ApiManagerProvider.manager.session.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in
    //        dataTasks.forEach { $0.cancel() }
    //        uploadTasks.forEach { $0.cancel() }
    //        downloadTasks.forEach { $0.cancel() }
    //    }
}


